<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="45%"
    @close="emit('close')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="add-webservicepolicy w-[100%]">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="110px"
        label-position="left"
        class="w-90%"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="地区" prop="areaId">
              <el-select
                v-model="formData.areaId"
                placeholder="请选择地区"
                @change="handleAreaChange"
                clearable
              >
                <template v-for="item in areaList" :key="item.id">
                  <el-option :label="item.label" :value="item.value" />
                </template>
                <!-- 这里可以添加其他上级导航选项 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" class="ml-20px">
            <el-form-item label="语言" prop="language">
              <el-select
                v-model="formData.language"
                placeholder="请选择语言"
                @focus="handleLanguageFocus"
                clearable
              >
                <template v-for="item in languageList" :key="item.id">
                  <el-option :label="item.label" :value="item.value" />
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="政策是否通用" prop="navigationType" class="webservicepolicy-switch">
          <el-switch
            class="block"
            v-model="formData.policyGeneral"
            active-color="#3721FF"
            inactive-color="#ccc"
            :active-text="formData.policyGeneral == 0 ? '是' : '否'"
            :active-value="0"
            :inactive-value="1"
            @change="handlePolicyGeneralChange"
          /><!--网站这边都是0是1否-->
          <span class="text-[12px] text-[#999] block mt-2">
            开启后，首页、商品列表页、商品落地页、订单提交页下的政策会共用一套</span
          >
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="使用权限" prop="dataScope">
              <el-radio-group v-model="formData.dataScope">
                <el-radio label="0">仅自己</el-radio>
                <el-radio label="1">所有人</el-radio>
                <el-radio label="3">指定人员</el-radio>
              </el-radio-group>
              <div class="block">
                <div v-if="formData.dataScope == '3'" class="flex">
                  <el-button type="primary" color="#3721FF" @click="handleSelectUser">
                    选择人
                  </el-button>
                  <div class="ml-2">
                    <!-- 最大只显示三个名字，多的后+几个人 -->
                    <template v-for="(item, index) in userList" :key="index">
                      <el-button type="primary" plain color="#3721FF" v-if="index < 3">
                        <span>{{ item.nickName }}</span>
                        <Icon
                          icon="material-symbols-light:cancel"
                          class="ml-2 text-[#999]"
                          @click.stop="handleRemoveUser(index)"
                        />
                      </el-button>
                    </template>
                    <span class="ml-2 text-[#3721FF" v-if="userList?.length > 3">
                      ... {{ userList?.length - 3 }}人</span
                    >
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="tabs">
        <el-tabs class="w-[100%] min-h-[300px] webservicepolicyTabs" v-model="activeTab">
          <el-tab-pane :label="item.label" v-for="(item, index) in tabsList" :key="index">
            <div
              class="ml-20px mr-20px mt-20px"
              v-for="(itm, idx) in item.navigationContent"
              :key="idx"
            >
              <div class="">
                <p class="flex justify-between">
                  <span>政策标题</span>
                  <span class="cursor-pointer" @click="removePolicy(index, idx)">
                    <Icon icon="material-symbols:cancel" />
                  </span>
                </p>
                <div class="w-[100%] flex items-center justify-between mt-10px">
                  <div class="w-[50%]">
                    <el-input v-model="itm.title" placeholder="请输入政策标题" />
                  </div>
                  <el-button
                    type="primary"
                    color="#3721FF"
                    @click="handleTemplateCenter(index, idx)"
                  >
                    <Icon icon="mdi-light:lightbulb-on" :size="16" />
                    模板中心
                  </el-button>
                </div>
              </div>
              <div>
                <span class="block pt-10px">政策描述</span>
                <div>
                  <Editor v-model="itm.detail" height="150px" class="mt-10px" />
                </div>
              </div>
            </div>
            <div>
              <el-button
                color="#3366ff"
                type="primary"
                class="mt-10px"
                @click="addPolicy(index, idx)"
              >
                <Icon icon="ep:plus" :size="10" /> 添加政策
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('close')">取消</el-button>
        <el-button type="primary" color="#3721FF" @click="submit">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <TemplatePolicyList :show-dot="true" ref="templatePolicyListRef" width="50%" @selected-template-policy="handleSelectedTemplatePolicy" />
  <SelectUsers ref="selectUserRef" @select-user="updateSelectUser" :userList="userList" />
</template>

<script setup lang="ts">
defineOptions({ name: 'AddWebservicepolicy' })
import TemplatePolicyList from './templatePolicyList.vue'
import SelectUsers from '@/components/SelectUser/index.vue'
import { WebServicePolicyApi } from '@/api/website/webservicepolicy'
import { throttle } from '@/utils'

import {
  getDeptList,
  getUserList,
  handleGetGlobeState,
  handleGetGlobeStateByIdList
} from '@/utils/index'
const props = defineProps(['isAddwebservicepolicy', 'selectedId', 'isAddCopy'])
const emit = defineEmits(['close', 'refresh'])
const dialogVisible = ref(true)
const selectUserRef = ref()
const Sindex = ref(null)
const Sidx = ref(null)
const areaList = ref([]) //地区
const languageList = ref([]) //语言
const userList = ref([])
const activeTab = ref('0')
const templatePolicyListRef = ref()
const title = ref('添加政策')
const formData = ref({
  name: '',
  areaId: '',
  language: '', // 语言
  policyGeneral: 1,
  dataScope: '1', // 使用权限
  dataScopeUserIds: [], // 数据范围用户id
  servicePolicyDetails: [],
  navigationContent: []
})
const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  language: [{ required: true, message: '请选择语言', trigger: 'change' }]
}
const tabsList = ref([
  {
    label: '首页',
    value: '0',
    navigationContent: [{ detail: '', title: '', type: '1' }]
  },
  {
    label: '商品列表页',
    value: '1',
    navigationContent: [{ detail: '', title: '', type: '2' }]
  },
  {
    label: '商品落地页',
    value: '2',
    navigationContent: [{ detail: '', title: '', type: '3' }]
  },
  {
    label: '订单提交页',
    value: '3',
    navigationContent: [{ detail: '', title: '', type: '4' }]
  },
  {
    label: '下单成功页',
    value: '4',
    navigationContent: [{ detail: '', title: '', type: '5' }]
  }
])
const formRef = ref<InstanceType<typeof ElForm>>()
const addPolicy = (index, idx) => {
  let activeTabs = tabsList.value.find((tab) => tab.value == activeTab.value)
  if (activeTabs) {
    activeTabs.navigationContent.push({
      // id: Date.now(),
      detail: '',
      title: '',
      type: (Number(activeTab.value) + 1).toString()
    })
  }
}
const handlePolicyGeneralChange = (val) => {
  if(formData.value.policyGeneral == 0){
    // 如果选中的是0，就把所有的数据改成跟第一条一样
    tabsList.value.map((tab) => {
      tab.navigationContent.map((item) => {
        item.detail = tabsList.value[0].navigationContent[0].detail
        item.title = tabsList.value[0].navigationContent[0].title
      })
    })
  }
}
// 删除
const removePolicy = (index, idx) => {
  tabsList.value[index].navigationContent.splice(idx, 1)
}
// 清空form表单
const resetForm = () => {
  console.log('清空form表单666');
  formRef.value?.resetFields()
  
}
// 回显
const handleGetWebServicePolicy = async () => {
  const res = await WebServicePolicyApi.getWebServicePolicy(props.selectedId)
  formData.value = res
  formData.value.dataScope = res.dataScope.toString()
  userList.value = res.userList?.map((item) => ({
    userId: item.id,
    nickName: item.nickname
  }))
  handleServicePolicyDetailListByServicePolicyId()
}
const handleServicePolicyDetailListByServicePolicyId = async () => {
  const res = await WebServicePolicyApi.getServicePolicyDetailListByServicePolicyId(
    props.selectedId
  )
  // 清空原有的 navigationContent
  tabsList.value.forEach((tab) => {
    tab.navigationContent = []
  })
  // 根据 type 将数据分配到对应的 tab
  res.forEach((item) => {
    const tabIndex = parseInt(item.type) - 1 // type 是 '1'~'5'，对应 tabsList 的索引 0~4
    if (tabIndex >= 0 && tabIndex <= tabsList.value.length) {
      tabsList.value.map((tab) => {
        if(tabIndex == Number(tab.type)){
          
        }
        
      })
      tabsList.value[tabIndex].navigationContent.push({
        detail: item.detail,
        title: item.title,
        type: item.type
      })
     

    }
  })
}
const handleSelectedTemplatePolicy = (val) =>{
    tabsList.value[Sindex.value].navigationContent[Sidx.value].detail = val.detail
    tabsList.value[Sindex.value].navigationContent[Sidx.value].title = val.title
}
// 提交
const submit = throttle(() => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      console.log('areaList', areaList.value)
      formData.value.servicePolicyDetails = tabsList.value.flatMap((tab) => tab.navigationContent)
      formData.value.area = areaList.value.find(
        (item) => item.value == formData.value.areaId
      )?.label
      if (
        props.selectedId &&
        (!props.isAddCopy ||
          props.isAddCopy == false ||
          props.isAddCopy == 'false' ||
          props.isAddCopy == undefined)
      ) {
        // formData.value.dataScopeUserIds = formData.value.userList.map((item) => item.id)
        console.log(formData.value.dataScopeUserIds, 'formData.value.dataScopeUserIds')

        delete formData.value.userList
        await WebServicePolicyApi.updateWebServicePolicy(formData.value)
      } else {
        if (props.isAddCopy) {
          formData.value.id = ''
        }
        await WebServicePolicyApi.createWebServicePolicy(formData.value)
      }
      emit('refresh')
      emit('close')
    } else {
      console.log('error submit!')
      return false
    }
  })
},  1000)
// -----------------------
// 以下是选择指定人员
const handleSelectUser = () => {
  selectUserRef.value?.open()
}
const handleRemoveUser = (index) => {
  userList.value.splice(index, 1)
  console.log(userList.value, 'userList.value')

  formData.value.dataScopeUserIds = userList.value.map((item) => item.userId)
  console.log('formData.value.dataScopeUserIds', formData.value.dataScopeUserIds)
}
const updateSelectUser = (data) => {
  formData.value.dataScopeUserIds =
    formData.value.dataScopeUserIds == undefined ? [] : formData.value.dataScopeUserIds
  userList.value = data.map((item) => ({
    userId: item.id,
    nickName: item.name
  }))
  formData.value.dataScopeUserIds.push(...data.map((item) => item.id)) // 添加到表单中
}
// ---------------------
// 根据地区获取语言
const handleAreaChange = async (val) => {
  languageList.value = await handleGetGlobeStateByIdList(val)
  formData.value.language = ''
}
// 根据地区获取语言
const handleLanguageFocus = async () => {
  if (!formData.value.areaId) {
    ElMessage.warning('请先选择地区')
  }
}

const handleTemplateCenter = (index, idx) => {
  // 模拟打开模板中心
  console.log(`打开模板中心，当前标签索引: ${index}, 政策索引: ${idx}`)
  templatePolicyListRef.value.show(index, idx)
  Sindex.value = index
  Sidx.value = idx
}
watch(
  () => props.isAddwebservicepolicy,
  (val) => {
    dialogVisible.value = val
  }
)
watch(dialogVisible, (val) => {
  if (!val) {
    emit('close')
  }
})

onMounted(async () => {
  // deptList.value = await getDeptList()
  areaList.value = await handleGetGlobeState() //获取地区
  console.log('props.selectedId88888', props.selectedId)

  if (props.selectedId) {
    handleGetWebServicePolicy()
    title.value = '编辑政策'
  }else{
    resetForm()
    title.value = '添加政策'
  }
})
// 抛出resetForm
defineExpose({
  resetForm
})
</script>

<style scoped>
@import '@/styles/theme.scss';
.webservicepolicy-switch :deep(.el-form-item__content) {
  display: block !important;
}
.webservicepolicyTabs :deep(.el-tabs__nav-scroll) {
  background-color: #f7f7fb;
  padding: 0 20px;
  box-sizing: border-box;
}
:deep(.is-top .is-active),
:deep(.is-top:hover),
:deep(.is-top .el-tabs__active-bar) {
  color: #3721ff;
}
:deep(.is-top .el-tabs__active-bar) {
  background-color: #3721ff;
}
</style>
